
# -*- coding: utf-8 -*-
#   私有控件，主体为lineEdit,附带PushButton命令按钮
# @Time    ： 2024/5/7  23:01
# @Auther  ： 徐良
# File     :  lineEdits.py
from PySide6.QtGui import QKeyEvent
from PySide6.QtWidgets import QApplication, QWidget, QLineEdit, QPushButton, QHBoxLayout, QFileDialog
from PySide6.QtCore import Qt


class LineEditPath(QWidget):
    """
    文件查找组件
    """
    def __init__(self, pdict=None, parent=None):
        super().__init__(parent)
        self.initUI()

    def initUI(self):
        # 创建水平布局
        layout = QHBoxLayout()
        layout.setSpacing(0)  # 将布局中的间距设置为0

        # 创建QLineEdit和QPushButton
        self.lineEdit = QLineEdit()
        self.lineEdit.setPlaceholderText('点击右边...按钮，选择路经')
        self.lineEdit.setMaximumHeight(20)
        self.commandButton = QPushButton("...")
        self.commandButton.setFixedSize(20, 20)  # 设置按钮大小为20x20像素

        # 添加控件到布局中
        layout.addWidget(self.lineEdit)
        layout.addWidget(self.commandButton)

        # 清除标题和边距
        self.setWindowFlags(Qt.Widget)
        layout.setContentsMargins(0, 0, 0, 0)

        self.setMaximumHeight(20)

        # 设置布局到自定义控件
        self.setLayout(layout)

        # 连接按钮的点击信号到槽函数
        self.commandButton.clicked.connect(self.selectFolder)

        # 应用样式
        self.setStyleSheet("""
            QLineEdit {
                border: 1px solid #ccc;  /* 设置边框 */
                border-radius: 3px;  /* 设置圆角 */
                padding: 1px;  /* 设置内边距 */
                font-size: 12px;  /* 设置字体大小 */
            }
            QPushButton {
                background-color: #007bff;  /* 设置背景颜色 */
                border: none;  /* 移除边框 */
                color: #fff;  /* 设置文字颜色 */
                border-radius: 5px;  /* 设置圆角 */
            }
            QPushButton:hover {
                background-color: #0056b3;  /* 设置鼠标悬停时的背景颜色 */
            }
            QPushButton:pressed {
                background-color: #003366;  /* 设置按钮按下时的背景颜色 */
            }
        """)

    def openFileDialog(self):
        file_dialog = QFileDialog(self)
        file_dialog.setFileMode(QFileDialog.ExistingFile)
        file_dialog.setNameFilter("All Files (*)")

        if file_dialog.exec():
            selected_files = file_dialog.selectedFiles()
            if selected_files:
                self.lineEdit.setText(selected_files[0])

    def selectFolder(self):
        folder_path = QFileDialog.getExistingDirectory(self, "选择文件夹", "/")
        if folder_path:
            self.lineEdit.setText(folder_path)
            # 模拟按下回车键事件
            key_event = QKeyEvent(QKeyEvent.KeyPress, Qt.Key_Return, Qt.NoModifier)
            QApplication.sendEvent(self.lineEdit, key_event)



